package com.apicloud.modulerecordscreen;

import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.os.Build;
import android.os.Handler;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 截屏、截图控制对象
 */
public class RecordScreen {
    private static final String TAG = "RecordScreen";

    private static final int STATUS_INIT = 0; //初始化
    private static final int STATUS_CONFIGED = 1; //配置完成
    private static final int STATUS_READY = 2; //准备就绪
    private static final int STATUS_RUNING = 3; //录制中
    private static final int STATUS_PAUSE = 4; //暂停
    private static final int STATUS_RELEASED = 5; //释放

    private static int status = 5; //当前状态
    private static MediaProjection mediaProjection;
    private static MediaRecorder mediaRecorder;
    private static VirtualDisplay virtualDisplay; //录屏的虚拟显示器:

    //初始化 传入MediaProjection对象
    public String create(MediaProjection mp){
        if(status != STATUS_RELEASED) release();
        mediaProjection = mp;
        mediaRecorder = new MediaRecorder();
        status = STATUS_INIT;
        return null;
    }
    /**
     * 开始录制
     * @param filePath 输出文件地址
     * @param width 视频分辨率-宽
     * @param height 视频分辨率-高
     * @param dpi dpi
     * @param bitrate 比特率
     * @param fps FPS
     */
    public String start(String filePath, int width, int height, int dpi, int orientation, int bitrate, int fps) {
        //如果在录制，就暂停了重新录
        if(status == STATUS_RELEASED) return "录屏项目已释放，需要重新创建";
        if(status != STATUS_INIT){
            stop();
        }
        try{
            //设定视频源和音频源
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            //设定配置
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setOrientationHint(orientation);
            mediaRecorder.setOutputFile(filePath);
            mediaRecorder.setVideoSize(width, height);
            mediaRecorder.setVideoFrameRate(fps);
            mediaRecorder.setVideoEncodingBitRate(bitrate);
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
//        mediaRecorder.setMaxFileSize(1024*1024*200); //设定录制文件的大小限制，byte
//        mediaRecorder.setMaxFileSize(1000*60); //设定录制文件的时间限制
            status = STATUS_CONFIGED;
        }catch (Exception e){
            return "配置失败：" + e.getMessage();
        }

        try {
            mediaRecorder.prepare();
            status = STATUS_READY;
        } catch (IOException e) {
            return "初始化失败：" + e.getMessage();
        }

        try{
            //创建虚拟显示器，并绑定输出
            virtualDisplay = mediaProjection.createVirtualDisplay(TAG + "-display", width, height, dpi,
                    DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, mediaRecorder.getSurface(), null, null);
        }catch (Exception e){
            return "创建虚拟显示器失败：" + e.getMessage();
        }

        try {
            mediaRecorder.start(); //开始录制
            status = STATUS_RUNING;
        }catch (Exception e){
            return "开始失败：" + e.getMessage();
        }

        return null;
    }

    public String pause(){
        if(status == STATUS_RELEASED) return "录屏项目已释放，需要重新创建";
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return "版本不足，需要安卓7.0以上";
        if (status != STATUS_RUNING) return "当前录屏没有开始";
        mediaRecorder.pause();
        status = STATUS_PAUSE;
        return null;
    }
    public String resume(){
        if(status == STATUS_RELEASED) return "录屏项目已释放，需要重新创建";
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return "版本不足，需要安卓7.0以上";
        if (status != STATUS_PAUSE) return "当前录屏没有暂停";
        mediaRecorder.resume();
        status = STATUS_RUNING;
        return null;
    }
    /**
     * 停止录制
     */
    public String stop(){
        if(status == STATUS_RELEASED) return "录屏项目已释放，需要重新创建";
        if (virtualDisplay != null) {
            virtualDisplay.release();
            virtualDisplay = null;
        }
        if (status == STATUS_RUNING || status == STATUS_PAUSE) {
            mediaRecorder.stop();
        }
        mediaRecorder.reset();
        status = STATUS_INIT; //状态变成初始化
        return null;
    }
    /**
     * 停止录制，并且释放内存
     */
    public String release(){
        if (mediaRecorder != null) {
            stop();
            mediaRecorder.release();
            mediaRecorder = null;
        }
        if (mediaProjection != null) {
            mediaProjection.stop();
            mediaProjection = null;
        }
        status = STATUS_RELEASED; //状态变成已经释放
        return null;
    }

    //---截图----
    private ImageReader imageReader;
    private VirtualDisplay imgVd;
    private String imgFilePath;
    public String imgCapture(String filePath, int width, int height, int dpi) {
        if(status == STATUS_RELEASED) return "录屏项目已释放，需要重新创建";
        imgFilePath = filePath;
        imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 1);

        imgVd = mediaProjection.createVirtualDisplay(TAG + "-image-display", width, height, dpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, imageReader.getSurface(), null, null);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Image image = imageReader.acquireLatestImage();
                int width = image.getWidth();
                int height = image.getHeight();
                Image.Plane[] planes = image.getPlanes();
                ByteBuffer buffer = planes[0].getBuffer();
                int pixelStride = planes[0].getPixelStride();
                int rowStride = planes[0].getRowStride();
                int rowPadding = rowStride - pixelStride * width;

                Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
                bitmap.copyPixelsFromBuffer(buffer);
                try {
                    FileOutputStream fos = new FileOutputStream(imgFilePath);     //构建输出流
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.close();
//                imgVd.release();
            }
        }, 500);
        return null;
    }

}
